package com.example.pceb.service.Impl;

import com.example.pceb.entity.CooperationApplication;
import com.example.pceb.entity.SchoolAdmin;
import com.example.pceb.entity.School;
import com.example.pceb.entity.Enterprise;
import com.example.pceb.entity.SchoolEnterpriseCooperation;
import com.example.pceb.mapper.CooperationApplicationMapper;
import com.example.pceb.mapper.SchoolAdminMapper;
import com.example.pceb.mapper.SchoolMapper;
import com.example.pceb.mapper.EnterpriseMapper;
import com.example.pceb.mapper.ProjectPhaseInitiationMapper;
import com.example.pceb.mapper.ProjectPhaseContractMapper;
import com.example.pceb.mapper.ProjectPhaseStartMapper;
import com.example.pceb.mapper.ProjectPhaseMidtermMapper;
import com.example.pceb.mapper.ProjectPhaseCompletionMapper;
import com.example.pceb.entity.ProjectPhaseInitiation;
import com.example.pceb.entity.ProjectPhaseContract;
import com.example.pceb.entity.ProjectPhaseStart;
import com.example.pceb.entity.ProjectPhaseMidterm;
import com.example.pceb.entity.ProjectPhaseCompletion;
import com.example.pceb.service.CooperationApplicationService;
import com.example.pceb.service.SchoolEnterpriseCooperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Date;
import java.util.Map;

@Service
public class CooperationApplicationServiceImpl implements CooperationApplicationService {

    private static final Logger logger = LoggerFactory.getLogger(CooperationApplicationServiceImpl.class);

    @Autowired
    private CooperationApplicationMapper mapper;

    @Autowired
    private SchoolAdminMapper schoolAdminMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;
    
    @Autowired
    private SchoolEnterpriseCooperationService cooperationService;
    
    @Autowired
    private ProjectPhaseInitiationMapper initiationMapper;
    
    @Autowired
    private ProjectPhaseContractMapper contractMapper;
    
    @Autowired
    private ProjectPhaseStartMapper startMapper;
    
    @Autowired
    private ProjectPhaseMidtermMapper midtermMapper;
    
    @Autowired
    private ProjectPhaseCompletionMapper completionMapper;

    @Override
    public void submitApplication(CooperationApplication application) {
        // 验证必填字段
        if (application.getApplicantName() == null || application.getApplicantName().trim().isEmpty()) {
            throw new IllegalArgumentException("申请者名称不能为空");
        }
        
        if (application.getCooperationId() == null) {
            throw new IllegalArgumentException("合作项目ID不能为空");
        }
        
        if (application.getApplicationContent() == null || application.getApplicationContent().trim().isEmpty()) {
            throw new IllegalArgumentException("申请内容不能为空");
        }
        
        if (application.getProposal() == null || application.getProposal().trim().isEmpty()) {
            throw new IllegalArgumentException("合作方案不能为空");
        }
        
        if (application.getResourcesProvided() == null || application.getResourcesProvided().trim().isEmpty()) {
            throw new IllegalArgumentException("提供的资源不能为空");
        }
        
        // 设置默认值
        if (application.getApplicationStatus() == null || application.getApplicationStatus().trim().isEmpty()) {
            application.setApplicationStatus("待审核");
        }
        
        logger.info("准备插入申请数据，发布者用户名: {}", application.getPublisherUsername());
        int result = mapper.insert(application);
        logger.info("插入申请结果: {}", result);
    }

    @Override
    public List<CooperationApplication> getApplicationsByPublisher(String publisherUsername) {
        return mapper.selectByPublisherUsername(publisherUsername);
    }

    @Override
    public List<CooperationApplication> getApplicationsByPublisherType(String publisherType) {
        return mapper.selectByPublisherType(publisherType);
    }
    
    @Override
    public CooperationApplication getApplicationById(Long id) {
        return mapper.selectByIdWithCooperationInfo(id);
    }

    @Override
    @Transactional
    public void reviewApplication(CooperationApplication application) {
        // 设置审核时间
        application.setReviewTime(new Date());
        logger.info("更新申请，ID: {}, 状态: {}, 备注: {}", 
            application.getId(), application.getApplicationStatus(), 
            application.getReviewRemarks());
        
        // 更新申请状态
        int result = mapper.updateApplication(application);
        logger.info("更新申请结果: {}", result);
        if (result <= 0) {
            throw new RuntimeException("更新申请失败，影响行数: " + result);
        }
        
        // 如果审核通过，需要更新合作项目信息
        if ("已通过".equals(application.getApplicationStatus())) {
            // 获取申请详情，包括合作项目信息
            CooperationApplication fullApplication = mapper.selectByIdWithCooperationInfo(application.getId());
            if (fullApplication == null) {
                throw new RuntimeException("未找到申请信息");
            }
            
            // 获取合作项目信息
            SchoolEnterpriseCooperation cooperation = cooperationService.getById(fullApplication.getCooperationId());
            if (cooperation == null) {
                throw new RuntimeException("未找到合作项目信息");
            }
            
            // 根据发布者类型决定更新哪个字段
            if ("企业".equals(fullApplication.getPublisherType())) {
                // 企业发布的合作项目，学校申请通过，更新school_name
                cooperation.setSchoolName(fullApplication.getApplicantName());
                logger.info("企业发布项目，学校申请通过，更新school_name为: {}", fullApplication.getApplicantName());
            } else if ("学校".equals(fullApplication.getPublisherType())) {
                // 学校发布的合作项目，企业申请通过，更新enterprise_name
                cooperation.setEnterpriseName(fullApplication.getApplicantName());
                logger.info("学校发布项目，企业申请通过，更新enterprise_name为: {}", fullApplication.getApplicantName());
            }
            
            // 更新项目状态为"待立项"
            cooperation.setProjectStatus("待立项");
            logger.info("更新项目状态为: 待立项");
            
            // 更新合作项目信息
            boolean updateResult = cooperationService.updateCooperationInfo(cooperation);
            if (!updateResult) {
                throw new RuntimeException("更新合作项目信息失败");
            }
            logger.info("合作项目信息更新成功");
            
            // 在5个阶段表中分别插入记录
            insertProjectPhases(fullApplication.getCooperationId());
        }
    }
    
    @Override
    public List<CooperationApplication> getMyApplications(String username, String userType) {
        // 根据用户类型获取申请列表
        if ("enterprise".equals(userType)) {
            // 企业用户，获取企业提交的申请
            return mapper.selectMyApplicationsByPublisherUsername(username);
        } else if ("school".equals(userType)) {
            // 学校用户，获取学校提交的申请
            return mapper.selectMyApplicationsByPublisherUsername(username);
        }
        return null;
    }
    
    @Override
    public List<CooperationApplication> getProjectApplications(Long projectId) {
        // 获取指定项目的所有申请
        return mapper.selectByCooperationId(projectId);
    }
    
    @Override
    public void cancelApplication(Long id, String username) {
        // 验证申请是否存在且属于该用户
        CooperationApplication application = mapper.selectByIdWithCooperationInfo(id);
        if (application == null) {
            throw new IllegalArgumentException("申请不存在");
        }
        
        if (!username.equals(application.getApplicantName())) {
            throw new IllegalArgumentException("无权取消此申请");
        }
        
        if (!"待审核".equals(application.getApplicationStatus())) {
            throw new IllegalArgumentException("只能取消待审核的申请");
        }
        
        // 更新申请状态为已取消
        application.setApplicationStatus("已取消");
        application.setReviewTime(new Date());
        application.setReviewRemarks("申请者主动取消");
        
        int result = mapper.updateApplication(application);
        if (result <= 0) {
            throw new RuntimeException("取消申请失败");
        }
    }

    @Override
    public List<Map<String, Object>> getMyApplicationsWithProject(String username) {
        logger.info("查询我的申请，用户名: {}", username);
        List<Map<String, Object>> result = mapper.selectMyApplicationsWithProjectByPublisherUsername(username);
        logger.info("查询结果数量: {}", result != null ? result.size() : 0);
        if (result != null && !result.isEmpty()) {
            logger.info("第一条记录: {}", result.get(0));
        }
        return result;
    }

    @Override
    public SchoolEnterpriseCooperation selectProjectById(Long id) {
        logger.info("查询项目详情，项目ID: {}", id);
        SchoolEnterpriseCooperation project = mapper.selectProjectById(id);
        logger.info("查询结果: {}", project != null ? project.getProjectName() : "null");
        return project;
    }
    
    /**
     * 在5个阶段表中分别插入记录
     * @param projectId 项目ID
     */
    private void insertProjectPhases(Long projectId) {
        try {
            Date now = new Date();
            // 1. 立项阶段
            ProjectPhaseInitiation initiation = new ProjectPhaseInitiation();
            initiation.setProjectId(projectId);
            initiation.setStatus("未开始");
            initiation.setResponsiblePerson("暂无");
            initiation.setDescription("暂无");
            initiation.setStartTime(now);
            int result1 = initiationMapper.insert(initiation);
            logger.info("立项阶段记录插入结果: {}", result1);
            
            // 2. 合同签订阶段
            ProjectPhaseContract contract = new ProjectPhaseContract();
            contract.setProjectId(projectId);
            contract.setStatus("未开始");
            contract.setResponsiblePerson("暂无");
            contract.setDescription("暂无");
            contract.setStartTime(now);
            int result2 = contractMapper.insert(contract);
            logger.info("合同签订阶段记录插入结果: {}", result2);
            
            // 3. 项目启动阶段
            ProjectPhaseStart start = new ProjectPhaseStart();
            start.setProjectId(projectId);
            start.setStatus("未开始");
            start.setResponsiblePerson("暂无");
            start.setDescription("暂无");
            start.setStartTime(now);
            int result3 = startMapper.insert(start);
            logger.info("项目启动阶段记录插入结果: {}", result3);
            
            // 4. 中期检查阶段
            ProjectPhaseMidterm midterm = new ProjectPhaseMidterm();
            midterm.setProjectId(projectId);
            midterm.setStatus("未开始");
            midterm.setResponsiblePerson("暂无");
            midterm.setDescription("暂无");
            midterm.setStartTime(now);
            int result4 = midtermMapper.insert(midterm);
            logger.info("中期检查阶段记录插入结果: {}", result4);
            
            // 5. 结项阶段
            ProjectPhaseCompletion completion = new ProjectPhaseCompletion();
            completion.setProjectId(projectId);
            completion.setStatus("未开始");
            completion.setResponsiblePerson("暂无");
            completion.setDescription("暂无");
            completion.setStartTime(now);
            int result5 = completionMapper.insert(completion);
            logger.info("结项阶段记录插入结果: {}", result5);
            
            logger.info("项目阶段记录插入完成，项目ID: {}", projectId);
        } catch (Exception e) {
            logger.error("插入项目阶段记录失败，项目ID: {}", projectId, e);
            throw new RuntimeException("插入项目阶段记录失败: " + e.getMessage());
        }
    }
}